package cn.itcast.demo.locks;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
public class SimpleRedisLock implements RedisLock {

    private StringRedisTemplate redisTemplate;

    private String key;

    private String VALUE_PREFIX = UUID.randomUUID().toString();

    public SimpleRedisLock(StringRedisTemplate redisTemplate, String key) {
        this.redisTemplate = redisTemplate;
        this.key = key;
    }

    @Override
    public boolean tryLock(long releaseTime) {
        String value = VALUE_PREFIX + "_" + Thread.currentThread().getId();
        Boolean isSuccess = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
        return BooleanUtils.isTrue(isSuccess);
    }

    @Override
    public void unlock() {
        // 先取出value只，判断释放一致
        String id = redisTemplate.opsForValue().get(key);
        // 获取当前id
        String value = VALUE_PREFIX + "_" + Thread.currentThread().getId();
        // 判断
        if(StringUtils.equals(id, value)) {
            redisTemplate.delete(key);
        }
    }
}
